<!-- views/reconciliation/components/DataImportWizard.vue -->
<template>
  <el-drawer
    v-model="visible"
    :title="dialogTitle"
    direction="rtl"
    size="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-steps :active="currentStep" finish-status="success" simple>
      <el-step title="选择文件" />
      <el-step title="配置参数" />
      <el-step title="预览数据" />
      <el-step title="完成导入" />
    </el-steps>
    
    <div class="wizard-content">
      <!-- 步骤1: 选择文件 -->
      <div v-show="currentStep === 0" class="step-content">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls,.csv"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 Excel (.xlsx, .xls) 和 CSV 文件，大小不超过 50MB
            </div>
          </template>
        </el-upload>
        
        <div class="import-type-selector">
          <el-radio-group v-model="importType">
            <el-radio value="transaction">导入银行流水</el-radio>
            <el-radio value="order">导入销售订单</el-radio>
          </el-radio-group>
        </div>
      </div>
      
      <!-- 步骤2: 配置参数 -->
      <div v-show="currentStep === 1" class="step-content">
        <el-form 
          :model="importConfig" 
          label-width="120px" 
          label-position="left"
        >
          <el-form-item label="数据源类型">
            <el-select v-model="importConfig.dataSourceType" placeholder="请选择数据源类型">
              <el-option label="政采云格式" value="zcy" />
              <el-option label="标准格式" value="standard" />
              <el-option label="自定义格式" value="custom" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="日期格式">
            <el-select v-model="importConfig.dateFormat" placeholder="请选择日期格式">
              <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
              <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
              <el-option label="MM/DD/YYYY" value="MM/DD/YYYY" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="编码格式">
            <el-select v-model="importConfig.encoding" placeholder="请选择编码格式">
              <el-option label="UTF-8" value="utf-8" />
              <el-option label="GBK" value="gbk" />
              <el-option label="GB2312" value="gb2312" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="首行作为标题">
            <el-switch v-model="importConfig.firstRowAsHeader" />
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 步骤3: 预览数据 -->
      <div v-show="currentStep === 2" class="step-content">
        <div class="preview-header">
          <h4>数据预览 (前10行)</h4>
          <el-tag type="info">共 {{ parsedData.length }} 行数据</el-tag>
        </div>
        
        <el-table 
          :data="previewData" 
          height="300" 
          border
          size="small"
        >
          <el-table-column 
            v-for="(column, index) in previewColumns" 
            :key="index"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
          />
        </el-table>
      </div>
      
      <!-- 步骤4: 完成导入 -->
      <div v-show="currentStep === 3" class="step-content">
        <el-result 
          icon="success" 
          title="导入完成" 
          :sub-title="`成功导入 ${importResult.successCount} 条数据`"
        >
          <template #extra>
            <div class="import-summary">
              <div class="summary-item">
                <span class="label">成功导入:</span>
                <span class="value success">{{ importResult.successCount }}</span>
              </div>
              <div class="summary-item">
                <span class="label">失败记录:</span>
                <span class="value error">{{ importResult.failCount }}</span>
              </div>
              <div class="summary-item">
                <span class="label">重复记录:</span>
                <span class="value warning">{{ importResult.duplicateCount }}</span>
              </div>
            </div>
          </template>
        </el-result>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          v-if="currentStep > 0 && currentStep < 3" 
          @click="prevStep"
        >
          上一步
        </el-button>
        <el-button 
          v-if="currentStep < 2" 
          type="primary" 
          @click="nextStep"
          :disabled="!canNext"
        >
          下一步
        </el-button>
        <el-button 
          v-if="currentStep === 2" 
          type="primary" 
          @click="startImport"
          :loading="importing"
        >
          开始导入
        </el-button>
        <el-button 
          v-if="currentStep === 3" 
          type="primary" 
          @click="handleFinish"
        >
          完成
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Upload } from '@element-plus/icons-vue'

interface Props {
  modelValue: boolean
  importType: 'transaction' | 'order'
}

const props = defineProps<Props>()
const emit = defineEmits(['update:modelValue', 'import-success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const dialogTitle = computed(() => {
  return props.importType === 'transaction' ? '导入银行流水' : '导入销售订单'
})

const currentStep = ref(0)
const uploadRef = ref()
const selectedFile = ref<File | null>(null)
const importing = ref(false)

const importType = ref(props.importType)

const importConfig = ref({
  dataSourceType: 'standard',
  dateFormat: 'YYYY-MM-DD',
  encoding: 'utf-8',
  firstRowAsHeader: true
})

const parsedData = ref<any[]>([])
const importResult = ref({
  successCount: 0,
  failCount: 0,
  duplicateCount: 0
})

const previewColumns = computed(() => {
  if (parsedData.value.length === 0) return []
  const firstRow = parsedData.value[0]
  return Object.keys(firstRow).map((key, index) => ({
    prop: key,
    label: `列${index + 1}`,
    width: 120
  }))
})

const previewData = computed(() => {
  return parsedData.value.slice(0, 10)
})

const canNext = computed(() => {
  if (currentStep.value === 0) {
    return selectedFile.value !== null
  }
  return true
})

const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const startImport = async () => {
  importing.value = true
  try {
    // 模拟导入过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟导入结果
    importResult.value = {
      successCount: 950,
      failCount: 3,
      duplicateCount: 47
    }
    
    currentStep.value = 3
  } catch (error) {
    // 处理错误
  } finally {
    importing.value = false
  }
}

const handleFinish = () => {
  emit('import-success')
  handleClose()
}

const handleClose = () => {
  visible.value = false
  currentStep.value = 0
  selectedFile.value = null
  parsedData.value = []
  importResult.value = {
    successCount: 0,
    failCount: 0,
    duplicateCount: 0
  }
}

// 监听导入类型变化
watch(() => props.importType, (newVal) => {
  importType.value = newVal
})
</script>

<style scoped lang="scss">
.wizard-content {
  margin-top: 20px;
  
  .step-content {
    min-height: 300px;
    
    .upload-area {
      margin-bottom: 20px;
    }
    
    .import-type-selector {
      text-align: center;
      padding: 20px 0;
    }
    
    .preview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      h4 {
        margin: 0;
      }
    }
    
    .import-summary {
      .summary-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        
        .label {
          color: #606266;
        }
        
        .value {
          font-weight: 500;
          
          &.success {
            color: #67c23a;
          }
          
          &.error {
            color: #f56c6c;
          }
          
          &.warning {
            color: #e6a23c;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>